# -*- coding: utf-8 -*-
# Copyright © 2024 weidongkl <weidongkx@gmail.com>
import logging
import os
import shutil
from excavator.utils.output import ExcavatorJobOutput
from excavator.utils import get_random_str
from excavator.job.base import Job
from excavator.models.report import notify_err, notify_info
from excavator.group import PrepareGroup

logger = logging.getLogger("excavator.job")


class PrepareRpmDbPath(Job):
    group = PrepareGroup
    requires = ()
    provides = ()

    def run(self, *args, **kwargs):
        msg = "adapter rpmdb path"
        ExcavatorJobOutput.info(self.name, msg)
        logger.info(msg)
        sysimage_path = "/usr/lib/sysimage"
        new_rpm_db_path = "{}/rpm".format(sysimage_path)
        old_rpm_db_path = "/var/lib/rpm"
        if not os.path.exists(old_rpm_db_path) or os.path.islink(old_rpm_db_path):
            msg = "old db({}) is null,skip".format(old_rpm_db_path)
            logger.error(msg)
            notify_err(msg, self.name)
            return

        if os.path.exists(new_rpm_db_path):
            files = os.listdir(new_rpm_db_path)
            if len(files) > 1:
                try:
                    logger.info("backup old sysimage rpm db")
                    shutil.move(new_rpm_db_path, "/usr/lib/sysimage/rpm_{}".format(get_random_str(5)))
                except OSError as e:
                    logger.warning(e)
        else:
            os.makedirs(sysimage_path, exist_ok=True)

        if os.path.exists(old_rpm_db_path):
            try:
                logger.info("move old db path to new db path")
                shutil.move(old_rpm_db_path, new_rpm_db_path)
            except OSError as e:
                logger.warning(e)
        else:
            msg = "Automatic processing failed, please handle manually"
            logger.error(msg)
            notify_err(msg, self.name)
        os.symlink(new_rpm_db_path, old_rpm_db_path)
        notify_info("adapter rpmdb path success", self.name)
